package com.example.private_auto_install.tool;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 暂定，设定的网卡只有一个
 *
 * @Description: 操作linux
 * @Author: by
 * @Date: 2023-10-10
 **/
public class HandleLinux {

    /**
     * @param map
     * @return
     */
    public static List<String> exeResult(Map<String, String> map) {
        String host = map.get("host");  // 你的主机名

        String user = "root";  // 你的用户名
        String password = "admin@123";  // 你的密码
        String port = "22";  // 默认的SSH端口是22
        String command = map.get("command");
        Session session = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(user, host, Integer.parseInt(port));
            session.setPassword(password);

            // 首次连接，将提示是否接受主机的key，可以选择接受或者跳过
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            System.out.println("运行命令为：" + command);
            Map<String, List<String>> map1 = HandleLinux.exeCommand(session, command);
            List<String> list = new ArrayList<>();


            if (map1.get("false").size() > 0) {
                System.out.println("第一次运行结果为：" + map1.get("false").toString());
                //变异报错
                String msg = "编译过程中发生错误,错误为：\n";
                for (String str : map1.get("false")) {
                    msg += str + "\n";
                }
                list.add(msg);
            } else {
                System.out.println("正确执行**********************");
                list = map1.get("true");
            }
            session.disconnect();
            return list;
        } catch (Exception e) {
            e.printStackTrace();  // 处理异常
            return null;
        } finally {
            if (session != null) {
                session.disconnect();
            }
        }
    }

    /**
     * 执行命令，并将后台的输出全部放置到list中，返回
     *
     * @param session
     * @param map
     * @param path
     * @return
     * @throws JSchException
     * @throws IOException
     */
    private static Map<String, List<String>> exeCommand(Session session, String command) throws JSchException, IOException {
        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        channel.setCommand(command);
        InputStream in = channel.getInputStream();
        InputStream err = channel.getErrStream();
//        System.out.printf("命令"+command);
//        channel.setErrStream(System.err);
        channel.connect();
        Map<String, List<String>> map = new HashMap<>();

        List<String> list = new ArrayList<>();
        List<String> list_err = new ArrayList<>();
        // 接收输出
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) break;
                String msgResult = new String(tmp, 0, i);
                if (!StringUtils.isEmpty(msgResult)) {
                    System.out.println(msgResult);
                    if (msgResult.indexOf("\n") >= 0) {
                        String[] arr = msgResult.split("\n");
                        for (String a : arr) {
                            list.add(a);
                        }
                    } else {
                        list.add(msgResult);
                    }
                }

            }
            if (channel.isClosed()) {
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
            }
        }

        tmp = new byte[1024];
        while (true) {
            while (err.available() > 0) {
                int i = err.read(tmp, 0, 1024);
                if (i < 0) break;
                String msgResult = new String(tmp, 0, i);
                if (!StringUtils.isEmpty(msgResult)) {
                    System.out.println(msgResult);
                    if (msgResult.indexOf("\n") >= 0) {
                        String[] arr = msgResult.split("\n");
                        for (String a : arr) {
                            list_err.add(a);
                        }
                    } else {
                        list_err.add(msgResult);
                    }
                }

            }
            if (channel.isClosed()) {
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
            }
        }
        map.put("true", list);
        map.put("false", list_err);

        // 等待命令执行完成
        int exitStatus = channel.getExitStatus();
        System.out.println("Exit status: " + exitStatus);

        channel.disconnect();
        return map;
    }

    private static void copyStream(InputStream in, OutputStream out, ChannelExec channel) throws IOException {
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) break;
                String msgResult = new String(tmp, 0, i);
                System.out.printf(msgResult);

            }
            if (channel.isClosed()) {
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
            }
        }
    }

    public static void main(String[] args) {
        test1();
//        test2();
    }

    public static void test1() {
        String path = "/home/cTest/4008.c";
        Map<String, String> map = new HashMap<>();
        map.put("user", "root");
        map.put("password", "admin@123");
        map.put("host", "192.168.121.55");
        map.put("port", "22");
        map.put("command1", path);
        map.put("command2", path.split("\\.")[0]);
        List<String> list = HandleLinux.exeResult(map);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
            if (i < list.size() - 1) {
                sb.append("\n");
            }
        }
        String result = sb.toString();
        System.out.println(result);
    }

    public static void test2() {
        String path = "D:/test1.c";
        BufferedReader reader = null;
        String CStr = "";
        try {
            reader = new BufferedReader(new FileReader(path));
            String line;
            while ((line = reader.readLine()) != null) {
                // 处理每一行，例如打印到控制台
                CStr += line + "\n";
//                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(CStr);
    }


}
